import { Injectable } from '@nestjs/common';
import { LoggerService } from 'src/modules/logger/logger.service';

@Injectable()
export class ParallercontrolService {
  constructor(private readonly loggerService: LoggerService) {}

  /**
   * 运行一组并行任务，控制最大并发数
   * @param taskList 任务列表
   * @param limit 最大并发数，默认为3
   * @returns 任务执行结果数组
   */
  run(
    taskList: Array<() => Promise<any>>,
    limit: number = 3,
    isLog: boolean = false,
  ) {
    // 创建工作区
    const works = new Array(limit).fill(null);
    const result = [];
    let index = 0;
    const tasks = works.map(() => {
      return new Promise((resolve) => {
        const next = async () => {
          let prevIndex = index;
          const task = taskList[index++];
          if (index > taskList.length) {
            resolve(null);
            return;
          }
          try {
            const res = await task();
            result[prevIndex] = res;
            if (isLog) {
            }
          } catch (error) {
            if (isLog) {
              // console.log(error, `任务${prevIndex}执行失败`);
              this.loggerService.logHttpRequestError(
                error,
                error.url,
                error.code,
              );
            }
            result[prevIndex] = {
              isStatus: false,
              error,
            };
          }
          next();
        };
        next();
      });
    });
    return Promise.all(tasks).then(() => {
      return result;
    });
  }
}
